package xdu.lz.stage7_jucCollection.lock_free;


import lombok.Data;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created at 2019/10/30 0030 下午 12:15
 * --
 */

public class LockFreeQueue<E> {
    private static class Node<E>{
        E element;
        volatile Node<E> next;

        public Node(E element) {
            this.element = element;
        }
    }

    private AtomicReference<Node<E>>  head,tail;

    private AtomicInteger size = new AtomicInteger(0);

    public LockFreeQueue() {
        Node<E> node = new Node<>(null);
        //reference the node
        this.head = new AtomicReference<>(node);
        //reference the node
        this.tail = new AtomicReference<>(node);
    }

    public void addLast(E e){
        //如果允许为null，判断很麻烦是否是头
        if(e == null){
            throw new RuntimeException("not allowed null");
        }
        Node<E> newNode = new Node<>(e);
        //多线程下保证了线程安全。
        //tail利用了CAS算法，把tail设定为newNode，1.7利用自旋，1.8底层利用CPU的CAS
        //tail is newNode
        Node<E> oldTail = tail.getAndSet(newNode);
        //preTail next is tail
        oldTail.next = newNode;
    }

}
